//
// Created by 罗俊华 on 2022/1/20.
//

#include "strngbad.h"
#include <iostream>

void show(const StringBad &input);


void shortest_and_first_char(const StringBad sayings[], const int total);

void shortest_and_first_char_by_pointer(const StringBad sayings[], const int total);

using std::cin;
using std::cout;
using std::endl;

int main() {

    StringBad arr[] = {
            "a fool and his money are soon parted",
            "penny wise, pound foolish",
            "the love of money is the root of much evil",
            "out of sight, out of mind",
            "absence makes the heart grow fonder",
            "absinthe makes the hart grow fonder",
    };

//    shortest_and_first_char(arr, 6);
    shortest_and_first_char_by_pointer(arr, 6);
//    input_and_show_each_character();
    return 0;
}

void input_and_show_each_character() {
    StringBad input;
    cin >> input;

    show(input);

    for (int i = 0; i < input.size(); ++i) {
        input[i] = char(97 + i);
    }

    show(input);

    cout << "遍历常量字符串";

    const StringBad const_str = "i'am a constant";

    show(const_str);
    cout << input;
}

void show(const StringBad &input) {
    for (int i = 0; i < input.size(); ++i) {
        cout << "第" << i << "个元素是：" << input[i] << endl;
    }

    cout << "==================>" << endl;
}

/**
 * 找出最短的谚语，并找到按字母表排序后的第一条谚语
 * @param sayings
 * @param total
 */
void shortest_and_first_char(const StringBad sayings[], const int total) {

    int shortest = 0;
    int first = 0;

    for (int i = 1; i < total; i++) {
        if (sayings[i].size() < sayings[shortest].size())
            shortest = i;
        if (sayings[i] < sayings[first])
            first = i;
    }
    cout << "Shortest saying:\n" << sayings[shortest] << endl;;
    cout << "First alphabetically:\n" << sayings[first] << endl;
    cout << "This program used " << StringBad::HowMany()
         << " String objects. Bye.\n";
}

/**
 * 通过指针的方式查找最长与最短
 * @param sayings
 * @param total
 */
void shortest_and_first_char_by_pointer( StringBad sayings[], const int total) {

    // use pointers to keep track of shortest, first strings
    StringBad *shortest = &sayings[0]; // initialize to first object
    StringBad *first = &sayings[0];
    for (i = 1; i < total; i++) {
        if (sayings[i].size() < shortest->size())
            shortest = sayings + i;//&sayings[i];
        if (sayings[i] < *first)     // compare values
            first = sayings + i;//&sayings[i];     // assign address
    }
    cout << "Shortest saying:\n" << *shortest << endl;
    cout << "First alphabetically:\n" << *first << endl;

}